import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author wcj
 * @Date 2021/6/8 11:34
 * @Version 1.0
 */
public class WaitNotify {
    static boolean flag = true;
    static Object lock = new Object();

    /**
     * 虽然不是经典的等待者消费者模式，但是基本思想基本一致
     * 等待者等待获取锁资源，如果获取到了，判断条件是否满足，满足的话进行相应操作，不满足继续等待
     * 通知者获取锁，如果获取到了进行相应操作，更改条件并唤醒等待者
     *
     * @param args
     */
    public static void main(String[] args) {
        Thread wait = new Thread(new Wait(), "Wait");
        wait.start();
        SleepUtils.second(1);
        Thread notify = new Thread(new Notify(), "Notify");
        notify.start();
    }

    /**
     * 等待者----消费者
     */
    static class Wait implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                while (flag) {
                    System.out.println(Thread.currentThread().getName() + " need wait:" + new SimpleDateFormat("HH:mm:ss").format(new Date(0)));
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " need operation:" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            }
        }
    }

    /**
     * 唤醒者----生产者
     */
    static class Notify implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + ":" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notify();
                flag = false;
                SleepUtils.second(100);
            }
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + ":" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            }
        }
    }
}
